package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RequestMapping("/admin/common")
@RestController
public class CommonController {

    // 导入aliOssUtil工具实体类
    private final AliOssUtil aliOssUtil;

    public CommonController(AliOssUtil aliOssUtil) {
        this.aliOssUtil = aliOssUtil;
    }

    @PostMapping("/upload")
    public Result<Object> upload(MultipartFile file){
        // 1. 使上传文件名随机化
        // 1.1 拿到原始文件名 以便获取后缀
        String originalFilename = file.getOriginalFilename();
        log.info("文件上传,原始文件名: {}",originalFilename);
        String suffix;

        if (originalFilename !=null) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }else {
            suffix = "";
        }

        // 1.2 随机名生成
        String uploadName = UUID.randomUUID() + "." + suffix;

        // 拿到上传文件
        String uploadUrl = null;
        try {
            uploadUrl = aliOssUtil.upload(file.getBytes(), uploadName);
        } catch (IOException e) {
            log.error("文件上传失败！！！{}", e.getMessage());
            return Result.error("文件上传失败");
        }

        // 返回图片地址
        return Result.success(uploadUrl);
    }
}
